#include "gconsos.h"
#include "ui_gconsos.h"
#include "moneydelegate.h"
#include <iostream>

bool allowEdit = false;

GConsos::GConsos(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GConsos)
{
    ui->setupUi(this);

    db = QSqlDatabase::database("user");

    QSettings s;

    modelCategories = new QSqlQueryModel(this);
    QSqlQuery q(db);
    q.prepare("SELECT * FROM categories WHERE get_racine(id) = :c");
    q.bindValue(":c",s.value("categorie_racine").toInt());
    q.exec();
    modelCategories->setQuery(q);
    ui->combo_filtre_categorie->setModel(modelCategories);
    ui->combo_filtre_categorie->setModelColumn(2);
    ui->combo_filtre_categorie->setCurrentIndex(0);
    ui->categorie->setModel(modelCategories);
    ui->categorie->setModelColumn(2);

    QVBoxLayout *layout = new QVBoxLayout(this);
    GCategories *gcat = new GCategories(this);
    gcat->setRoot(s.value("categorie_racine").toInt());
    layout->addWidget(gcat);
    ui->pageCategorie->setLayout(layout);

    modCat = false;

    refresh();
}

GConsos::~GConsos()
{
    delete ui;
    delete current;
    delete save;
}

void GConsos::refresh()
{
    QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this, db);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setTable("consos");
    model->setJoinMode(QSqlRelationalTableModel::LeftJoin);
    model->setRelation(1, QSqlRelation("categories", "id", "nom"));

    QString filtre = "";
    filtre += "actif=";
    filtre.append(ui->checkBox_2->isChecked() ? '1' : '0');
    filtre += " and consos.nom like '%" + ui->text_filtre_nom->text() + "%'";
    if(ui->combo_filtre_categorie->currentIndex() > 0)
    {
        filtre += " and consos.categorie=";
        filtre.append(modelCategories->index(ui->combo_filtre_categorie->currentIndex(),0).data().toString());
    } else if (ui->combo_filtre_categorie->currentIndex() == 0) {
        filtre += " and get_racine(consos.categorie)=";
        filtre.append(modelCategories->index(ui->combo_filtre_categorie->currentIndex(),0).data().toString());
    }

    model->setFilter(filtre);
    model->select();
    model->setHeaderData(0, Qt::Horizontal, tr("ID"));
    model->setHeaderData(1, Qt::Horizontal, tr("Categorie"));
    model->setHeaderData(2, Qt::Horizontal, tr("Nom"));
    model->setHeaderData(3, Qt::Horizontal, tr("Commentaire"));
    model->setHeaderData(4, Qt::Horizontal, tr("Mots Clefs"));
    model->setHeaderData(5, Qt::Horizontal, tr("Prix en €"));
    model->setHeaderData(7, Qt::Horizontal, tr("Stock"));
    model->setHeaderData(6, Qt::Horizontal, tr("Actif"));

    ui->table_consos->setModel(model);
    ui->table_consos->hideColumn(0);


    MoneyDelegate *m1 = new MoneyDelegate(ui->table_consos);
    ui->table_consos->setItemDelegateForColumn(5,m1);

    ui->table_consos->resizeColumnsToContents();
}

void GConsos::clear_tab()
{
    if(current != NULL) delete current;
    if(save != NULL) delete save;

    ui->list_motsclefs->clear();
    ui->text_nom->setText("");
    ui->text_com->setText("");
    ui->spin_prix->setValue(0);
    ui->spin_stock->setValue(0);
    ui->list_motsclefs->clear();
    ui->categorie->setCurrentIndex(0);
    ui->check_actif->setChecked(false);
}

void GConsos::refresh_tab()
{
    if(current == NULL) return;

    ui->text_nom->setText(current->getNom());
    ui->text_com->setText(current->getCommentaire());
    ui->spin_prix->setValue(current->getPrix());
    ui->spin_stock->setValue(current->getStock());
    QStringList mc = current->getMotsclefs();
    ui->list_motsclefs->clear();
    for(int i=0; i<mc.count(); i++)
    {
        ui->list_motsclefs->addItem(mc.at(i));
    }
    ui->categorie->setCurrentText(current->getCategorieName());
    ui->check_actif->setChecked(current->getActif());

    refresh();
}

void GConsos::on_table_consos_clicked(const QModelIndex &index)
{
    enable_all(false);
    clear_tab();

    current = new consos(ui->table_consos->model()->data(ui->table_consos->model()->index(index.row(), 0)).toInt());
    save = new consos(ui->table_consos->model()->data(ui->table_consos->model()->index(index.row(), 0)).toInt());

    ui->toolBox->setCurrentIndex(0);

    refresh_tab();
    enable_all(true);
}

void GConsos::on_btn_add_motclef_clicked()
{
    if(current == NULL || !allowEdit) return;

    bool ok;
    QString mc;
    mc = QInputDialog::getText(this, "Nouveau mot clef", "Entrée le nouveau mot clef", QLineEdit::Normal, "", &ok);
    if(ok)
    {
        current->addMotsclefs(mc);
    }

    refresh_tab();
}

void GConsos::on_btn_sup_motclef_clicked()
{
    if(current == NULL || !allowEdit) return;

    current->delMotsclefs(ui->list_motsclefs->row(ui->list_motsclefs->selectedItems().at(0)));

    refresh_tab();
}

void GConsos::on_btn_stock_clicked()
{
    if(current == NULL || !allowEdit) return;

    bool ok1, ok2;
    int init, add;
    init = QInputDialog::getInt(this, "Stock présent", "Entrée le stock actuel", 0, 0, 200, 1, &ok1);
    add = QInputDialog::getInt(this, "Stock ajouté", "Entrée le stock ajouté", 0, 0, 200, 1, &ok2);
    if(ok1 && ok2)
    {
        current->setStock(init, add);
    }

    refresh_tab();
}

void GConsos::on_btn_annule_clicked()
{
    if(current == NULL || !allowEdit) return;

    save->updateDatabase();
    delete current;
    current = new consos(save->getId());

    refresh_tab();
}

void GConsos::on_text_nom_editingFinished()
{
    if(current == NULL || !allowEdit) return;

    current->setNom(ui->text_nom->text());

    refresh_tab();
}

void GConsos::on_text_com_editingFinished()
{
    if(current == NULL || !allowEdit) return;

    current->setCommentaire(ui->text_com->text());

    refresh_tab();
}

void GConsos::on_btn_nouveau_clicked()
{
    enable_all(false);
    clear_tab();

    bool ok;
    QString name = QInputDialog::getText(this, "Nouvelle Consos", "Entrée le nom de cette nouvelle consomation", QLineEdit::Normal, "", &ok);
    if(ok)
    {
        QSqlQuery q(db);

        q.prepare("INSERT INTO consos(categorie, nom, prix, actif, stock) VALUES (:c, :name, 1, 1, 0)");
        q.bindValue(":name", name);
        q.bindValue(":c",modelCategories->index(0,0).data().toInt());
        q.exec();

        QSqlQuery q2(db);

        q2.prepare("SELECT id FROM consos WHERE nom=:name AND prix=1 AND actif=1 AND stock=0");
        q2.bindValue(":name", name);
        q2.exec();

        if(q2.first())
        {
            current = new consos(q2.value(0).toInt());
            save = new consos(q2.value(0).toInt());
        }

        if(current!=NULL)
        {
            refresh_tab();
            enable_all(true);
            refresh();
            ui->text_com->setFocus(Qt::TabFocusReason);
        }
    }




}

void GConsos::on_spin_prix_editingFinished()
{
    if(current == NULL || !allowEdit) return;

    current->setPrix(ui->spin_prix->value());

    refresh_tab();
}

void GConsos::on_text_filtre_nom_textChanged(const QString &arg1)
{
    refresh();
}

void GConsos::on_checkBox_2_stateChanged(int arg1)
{
    refresh();
}

void GConsos::on_combo_filtre_categorie_currentIndexChanged(int index)
{
    refresh();
}


void GConsos::on_categorie_currentIndexChanged(int index)
{
    if(current == NULL || !allowEdit) return;

    current->setCategorie(modelCategories->index(index,0).data().toInt());

    refresh_tab();
}

void GConsos::on_check_actif_clicked()
{
    if(current == NULL || !allowEdit) return;

    current->setActif(!current->getActif());

    refresh_tab();
}

void GConsos::enable_all(bool on)
{
    allowEdit = on;

    ui->text_nom->setEnabled(on);
    ui->text_com->setEnabled(on);
    ui->categorie->setEnabled(on);
    ui->list_motsclefs->setEnabled(on);
    ui->btn_add_motclef->setEnabled(on);
    ui->btn_sup_motclef->setEnabled(on);
    ui->btn_annule->setEnabled(on);
    ui->btn_stock->setEnabled(on);
    ui->spin_prix->setEnabled(on);
    ui->check_actif->setEnabled(on);
}

void GConsos::on_toolBox_currentChanged(int index)
{

    if(index == 1){
        ui->pageConsos->setEnabled(false);
        ui->pageFiltre->setEnabled(false);
        ui->btn_nouveau->setEnabled(false);
        ui->table_consos->setEnabled(false);

        modCat = true;
    } else {

        ui->pageConsos->setEnabled(true);
        ui->pageFiltre->setEnabled(true);
        ui->btn_nouveau->setEnabled(true);
        ui->table_consos->setEnabled(true);

        if(modCat){
            QSettings s;

            QSqlQuery q(db);
            q.prepare("SELECT * FROM categories WHERE get_racine(id) = :c");
            q.bindValue(":c",s.value("categorie_racine").toInt());
            q.exec();
            modelCategories->setQuery(q);
            ui->combo_filtre_categorie->setCurrentIndex(0);
            ui->categorie->setCurrentIndex(0);
        }
        modCat = false;

    }

}
